package controller

import (
	"context"
	"log"
	"net/http"
	"strconv"

	"device-admin/internal/app/web/service/ws"

	"192.168.1.75/go-pkg/logx"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

type WS struct{}

var upgrader = websocket.Upgrader{
	// 解决跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// WebSocket 处理websocket
func (WS) WebSocket(c *gin.Context) {
	// 将http连接升级为websocket连接
	wsConn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	{
		if err != nil {
			log.Print("upgrade:", err)
			return
		}
		defer wsConn.Close()
	}

	logx.Info(context.Background(), "WebSocket connected")

	// 获取请求参数
	wsType := c.Query("ws_type")
	robotID := c.Query("robot_id") // 设备id

	// 处理不同的websocket类型
	switch wsType {
	case "robot_realtime_info": // 机器人实时信息
		ws.RobotRealtimeInfoHandle(wsConn, "robot_realtime_info", c.GetString("authorization"))
	case "robot_realtime_alarm_info": // 机器人实时告警信息
		ws.RobotRealtimeInfoHandle(wsConn, "robot_realtime_alarm_info", c.GetString("authorization"))
	case "webshell95": // 95命令行
		fileSizeStr := c.Query("file_size")
		fileSize, _ := strconv.ParseInt(fileSizeStr, 10, 64)
		ws.WebShell95Handle(wsConn, robotID, c.Query("dst_dir"), c.Query("file_name"), fileSize, c.Query("file_md5"), c.GetString("user_id"))
	case "chat": // 实时对讲
		ws.ChatHandle(wsConn, robotID)
	}
}
